package com.market.auto;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.market.entity.MaUser;
import com.market.mapper.MaUserMapper;
import com.market.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录成功操作
 */
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {
    @Autowired
    MaUserMapper maUserMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",SecurityContextHolder.getContext().getAuthentication().getName());
      MaUser anUser=  maUserMapper.selectOne(queryWrapper);
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
        Result result ;
        result=com.market.response.Result.ok().data("user",anUser);
        HttpSession session=request.getSession();
        session.setAttribute("user",anUser);
        //处理编码方式，防止中文乱码的情况
//        response.setContentType("text/json;charset=utf-8");
//        //塞到HttpServletResponse中返回给前台
//        //这是springboot中jackson给我们提供的一种能将类或者其他对象转成json的方式
//        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        this.WriteJSON(request,response,result);
    }
}